package com.gosophiaigit.contact.busi.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springside.core.dao.HibernateEntityDao;
import com.gosophia.commons.exception.BusinessException;
import com.gosophiaigit.common.busi.service.IGroupUtilService;
import com.gosophiaigit.contact.busi.entity.Contact;
import com.gosophiaigit.contact.busi.entity.ContactGroup;
import com.gosophiaigit.contact.busi.entity.ContactGroupRelation;
import com.gosophiaigit.contact.busi.service.IContactGroupService;
import com.gosophiaigit.contact.busi.service.IContactService;

/**
 * 组联系人操作实现
 * 
 * @author guodp
 * 
 */
@Service("contactGroupService")
@Transactional
@SuppressWarnings("unchecked")
public class ContactGroupServiceImpl implements IContactGroupService {

	@Autowired
	private HibernateEntityDao<?> hibernateEntityDao;
	@Autowired
	private IGroupUtilService groupUtilService;
	@Autowired
	private IContactService contactService;

	@Override
	public void addContactGroup(ContactGroup group) {
		Assert.notNull(group, "组信息不能为null");
		Assert.isNull(group.getGroupId(), "组信息Id必须为null");
		hibernateEntityDao.save(group);
	}

	@Override
	public void updateContactGroup(ContactGroup group) {
		Assert.notNull(group, "组信息不能为null");
		Assert.notNull(group.getGroupId(), "组信息Id不能为null");
		hibernateEntityDao.update(group);
	}

	@Override
	public boolean deleteContactGroup(Long groupId) {
		ContactGroup contactGroup = hibernateEntityDao.get(ContactGroup.class,
				groupId);

		if (contactGroup.getContactGroupRelations().size() > 0) {
			return false;
		} else {
			hibernateEntityDao.removeById(ContactGroup.class, groupId);
		}
		return true;
	}

	@Override
	public boolean exitPublicGroupName(Long groupId, String groupName) {
		Assert.notNull(groupName, "组名称不能为空！");
		if (groupId == null) {
			String hql = "from ContactGroup as group where group.groupName = ? and group.groupType = ?";
			List<?> list = hibernateEntityDao.find(hql, groupName,
					ContactGroup.PUBLIC_GROUP);
			if (list.size() > 0) {
				return true;
			}
		} else {
			List<?> list = hibernateEntityDao.find(
					"from ContactGroup as group where group.groupName = ? "
							+ "and groupId != ? and group.groupType = ?",
					groupName, groupId, ContactGroup.PUBLIC_GROUP);
			if (list.size() > 0) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public boolean exitPrivateGroupName(Long groupId, String groupName,
			Long contactId) {
		Assert.notNull(groupName, "组名称不能为空！");
		if (groupId == null) {
			String hql = "from ContactGroup as group where group.groupName=? and group.groupOwner=? and groupType=?";
			List<?> list = hibernateEntityDao.find(hql, groupName, contactId,
					ContactGroup.PRIVATE_GROUP);
			if (list.size() > 0) {
				return true;
			}
		} else {
			String hql = "from ContactGroup as group where group.groupId!=? and group.groupName=? and group.groupOwner=? and groupType=?";
			List<?> list = hibernateEntityDao.find(hql, groupId, groupName,
					contactId, ContactGroup.PRIVATE_GROUP);
			if (list.size() > 0) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public ContactGroup findContactGroupById(Long contactGroupId) {
		Assert.notNull(contactGroupId, "组信息ID不能为null");
		return hibernateEntityDao.get(ContactGroup.class, contactGroupId);
	}
	
	@Override
	public List<ContactGroup> findGroupListByGroupType(Long userInfoId,
			Long userAccountId, Long groupType) {
		Assert.notNull(userAccountId, "登录账号不能为空");
		Assert.notNull(groupType, "组类型不能为空");
		List<ContactGroup> groupList = new ArrayList<ContactGroup>();
		if (groupType == ContactGroup.PUBLIC_GROUP || userInfoId == null) {
			groupList = getCommonGroupListByGroupType();
		} else {
			groupList = getPersonalGroupListByGroupType(userInfoId);
		}
		List<ContactGroupRelation> groupPersonNumberlist = getGroupPersonNumber(userAccountId);
		return getContactGroupList(groupList, groupPersonNumberlist);
	}

	@Override
	public List<Contact> findAllContactList() {
		List<Contact> contactList = hibernateEntityDao.getAll(Contact.class);
		return contactList;
	}

	@Override
	public List<Contact> findContactByContactGroupId(Long contactGroupId,
			Long userAccountId) {
		Assert.notNull(contactGroupId, "组信息ID不能为null");
		boolean permission = groupUtilService
				.findPermissionByUserAccountId(userAccountId);
		String query_sql = "select c.contactid as contactId,u.username as contactName,c.useflag as contactUseFlag from igit_contact_group_relation r "
				+ "left join igit_contact c on r.contactid=c.contactid left join igit_contact_group g on r.groupid=g.groupid "
				+ "left join T_USERMANA_USERINFO u on u.userinfoid=c.userinfoid where (c.delflag is null or c.delflag <>1)";
		if (!permission) {
			query_sql += " and c.useflag=1";
		}
		query_sql += " and r.groupid=" + contactGroupId;
		Query query = hibernateEntityDao.getSessionFactory()
				.getCurrentSession().createSQLQuery(query_sql).addScalar(
						"contactId", Hibernate.LONG).addScalar("contactName")
				.addScalar("contactUseFlag", Hibernate.LONG)
				.setResultTransformer(Transformers.aliasToBean(Contact.class));
		List<Contact> resultList = query.list();
		return resultList;
	}

	
	@Override
	public List<Contact> findContactRecordCountList(Long userInfoId,
			Long userAccountId) {
		Long contactId = contactService.findContactByUserInfoId(userInfoId)
				.getContactId();
		List<Contact> resultList = new ArrayList<Contact>();
		if (contactId != null) {
			boolean permission = groupUtilService
					.findPermissionByUserAccountId(userAccountId);
			String query_sql = "select c.contactid as contactId,u.username as ContactName,c.useflag as contactUseFlag from "
					+ " (select distinct t.activecontactid from( select decode(activecontact,'"
					+ contactId
					+ "',passivecontact,activecontact) activecontactid,activecontact,passivecontact,recordid,contactdate from igit_contact_record "
					+ "order by contactdate desc) t where (t.passivecontact="
					+ contactId
					+ " or t.activecontact="
					+ contactId
					+ " )and rownum <=10) r left join igit_contact c "
					+ "on r.activecontactid=c.contactid left join t_usermana_userinfo u on c.userinfoid=u.userinfoid where (c.delflag is null or c.delflag <>1) ";
			if (!permission) {
				query_sql += " and c.useflag=1";
			}
			Query query = hibernateEntityDao.getSessionFactory()
					.getCurrentSession().createSQLQuery(query_sql).addScalar(
							"contactId", Hibernate.LONG).addScalar(
							"ContactName").addScalar("contactUseFlag",
							Hibernate.LONG).setResultTransformer(
							Transformers.aliasToBean(Contact.class));
			resultList = query.list();
		}
		return resultList;
	}

	@Override
	public List<Contact> findContactList(Long userAccountId) {
		boolean permission = groupUtilService
				.findPermissionByUserAccountId(userAccountId);
		String query_sql = "select c.contactid as contactId,u.username as ContactName,c.useflag as contactUseFlag from igit_contact c left join T_USERMANA_USERINFO u on u.userinfoid=c.userinfoid where (c.delflag is null or c.delflag <>1)";
		if (!permission) {
			query_sql += " and c.USEFLAG=1";
		}
		Query query = hibernateEntityDao.getSessionFactory()
				.getCurrentSession().createSQLQuery(query_sql).addScalar(
						"contactId", Hibernate.LONG).addScalar("ContactName")
				.addScalar("contactUseFlag", Hibernate.LONG)
				.setResultTransformer(Transformers.aliasToBean(Contact.class));
		List<Contact> resultList = query.list();
		return resultList;
	}

	/**
	 * 根据组类型得到公共组中的ID与每个组的名字的集合
	 */
	private List<ContactGroup> getCommonGroupListByGroupType() {
		String hql = "select new ContactGroup(g.groupId ,g.groupName) from ContactGroup g  where g.groupType=? group by g.groupName,g.groupId order by g.groupId ";
		return hibernateEntityDao.createQuery(hql, ContactGroup.PUBLIC_GROUP)
				.list();
	}

	/**
	 * 根据组类型和组拥有者ID得到拥有者的下个人组中的ID与每个组的名字的集合
	 */
	private List<ContactGroup> getPersonalGroupListByGroupType(Long userInfoId) {
		Long groupOwner = contactService.findContactByUserInfoId(userInfoId)
				.getContactId();
		if (groupOwner != null) {
			String hql = "select new ContactGroup(g.groupId ,g.groupName) from ContactGroup g  where g.groupType=? and g.groupOwner=? group by g.groupName,g.groupId order by g.groupId";
			return hibernateEntityDao.createQuery(hql,
					ContactGroup.PRIVATE_GROUP, groupOwner).list();
		}
		return null;
	}

	/**
	 * 得到每个组的ID与每个组下的人员数量的集合
	 */
	private List<ContactGroupRelation> getGroupPersonNumber(Long userAccountId) {
		boolean permission = groupUtilService
				.findPermissionByUserAccountId(userAccountId);
		String query_sql = "select r.groupid as relationId,count(c.contactid) as groupPersonNumber from igit_contact_group_relation r left join ";
		if (permission) {
			query_sql += "(select * from igit_contact i where (i.delflag is null or i.delflag <>1))";
		} else {
			query_sql += "(select * from igit_contact i where i.useflag=1 and (i.delflag is null or i.delflag <>1))";
		}
		query_sql += " c on r.contactid=c.contactid group by r.groupid";
		Query query = hibernateEntityDao.getSessionFactory()
				.getCurrentSession().createSQLQuery(query_sql).addScalar(
						"relationId", Hibernate.LONG).addScalar(
						"groupPersonNumber", Hibernate.INTEGER)
				.setResultTransformer(
						Transformers.aliasToBean(ContactGroupRelation.class));
		List<ContactGroupRelation> resultList = query.list();
		return resultList;
	}

	/**
	 * 根据联系人组别管理对象集合与组别联系人关系对象集合，拼合成联系人组和各组下人数的集合
	 */
	private List<ContactGroup> getContactGroupList(
			List<ContactGroup> groupList,
			List<ContactGroupRelation> groupPersonNumberlist) {
		List<ContactGroup> orderList = groupList;
		for (int i = 0; i < orderList.size(); i++) {
			ContactGroup contactGroup = orderList.get(i);
			for (int j = 0; j < groupPersonNumberlist.size(); j++) {
				ContactGroupRelation contactGroupRelation = groupPersonNumberlist
						.get(j);
				if (contactGroup.getGroupId().equals(
						contactGroupRelation.getRelationId())) {
					contactGroup.setGroupPersonNumber(contactGroupRelation
							.getGroupPersonNumber());
					orderList.set(i, contactGroup);
				}
			}
		}
		return orderList;
	}
	
	/**
	 * 添加联系人到指定组中
	 * @param 联系人 contact
	 * @param 联系人所在的组 contactGroup
	 */
	@Override
	public void addContactToGroup(List<Contact> contactList, ContactGroup contactGroup) {
		for(Contact contact : contactList){
			ContactGroupRelation contactGroupRelation = this.getRelationByGroupAndContact(contact, contactGroup);
			if(contactGroupRelation!=null){
				continue;
			}else{
				contactGroupRelation = new ContactGroupRelation();
				contactGroupRelation.setContact(contact);
				contactGroupRelation.setContactGroup(contactGroup);
				hibernateEntityDao.save(contactGroupRelation);
			}
		}
	}
	
	/**
	 * 移动联系人到指定组中
	 * @param 联系人 sourceGroup：当前组
	 * @param 联系人 contact：联系人
	 * @param 指定组 targetGroup：目标组
	 */
	@Override
	public void romoveContactToGroup(ContactGroup sourceGroup,List<Contact> contactList,ContactGroup targetGroup){
		//把联系人从当前组中移除
		if(sourceGroup!=null){
			this.removeContactFromGroup(contactList, sourceGroup);
		}
		//把联系人添加到目标组中
		this.addContactToGroup(contactList, targetGroup);
	}

	/**
	 * 从指定组中移除联系人
	 * @param 联系人 contact
	 * @param 联系人所在的组 contactGroup
	 */
	@Override
	public void removeContactFromGroup(List<Contact> contactList,ContactGroup contactGroup) {
		for(Contact contact : contactList){
			ContactGroupRelation relation = getRelationByGroupAndContact(contact, contactGroup);
			hibernateEntityDao.remove(relation);
		}
	}

	/**
	 * 根据联系人和组，得到组间关系对象：ContactGroupRelation
	 * @param contact 联系人
	 * @param contactGroup 联系人所在的组
	 * @return 组间关系对象：ContactGroupRelation
	 */
	private ContactGroupRelation getRelationByGroupAndContact(Contact contact,ContactGroup contactGroup){
		ContactGroupRelation relation =null;
		String hql = "from ContactGroupRelation r where r.contact=? and r.contactGroup=?";
		List<ContactGroupRelation> list = hibernateEntityDao.find(hql, contact,contactGroup);
		if (list != null && list.size() > 0) {
			relation = list.get(0);
		}
		return relation;
	}

	/**
	 * 得到当前用户所在的个人组，和所有的公共组
	 * @throws BusinessException 
	 */
	@Override
	public Map<String, List<ContactGroup>> getAllContactGroupByCurrentUserId(Long userInfoId,Long userAccountId) {

		Map<String, List<ContactGroup>> groupMap = new HashMap<String, List<ContactGroup>>();
		List<ContactGroup> commonGroupList = findGroupListByGroupType(null,userAccountId,ContactGroup.PUBLIC_GROUP);
		List<ContactGroup> personalGroupList = findGroupListByGroupType(userInfoId,userAccountId,ContactGroup.PRIVATE_GROUP);
		
		boolean flag = groupUtilService.findPermissionByUserAccountId(userAccountId);
		if(flag){//拥有管理权限 
			groupMap.put(ContactGroup.PUBLIC_GROUP+"", commonGroupList);
		}
		groupMap.put(ContactGroup.PRIVATE_GROUP+"", personalGroupList);
		
		return groupMap;
	}
	
	/**
	 * 查询所有的用户模糊查询方法 queryType 01所有用户组普通模糊查询02所有用户组按首字母模糊查询
	 */
	@Override
	public List<Contact> findUserInfoList(String contactQuery,
			String queryType, Long userAccountId) {
		boolean permission = groupUtilService.findPermissionByUserAccountId(userAccountId);
		String query_sql = "select c.contactid as contactId,u.username as ContactName,c.useflag as contactUseFlag from igit_contact c left join T_USERMANA_USERINFO u on u.userinfoid=c.userinfoid where (c.delflag is null or c.delflag <>1) ";
		if (!permission) {
			query_sql += " and c.USEFLAG=1";
		}
		if (queryType != null) {
			if (queryType.equals("01")) {
				query_sql += " and u.username like '%" + contactQuery + "%'";
			}
			if (queryType.equals("02")) {
				query_sql += " and regexp_like(c.spellname,'^[" + contactQuery
						+ "]')";
			}
		}
		Query query = hibernateEntityDao.getSessionFactory()
				.getCurrentSession().createSQLQuery(query_sql).addScalar(
						"contactId", Hibernate.LONG).addScalar("ContactName")
				.addScalar("contactUseFlag", Hibernate.LONG)
				.setResultTransformer(Transformers.aliasToBean(Contact.class));
		List<Contact> resultList = query.list();
		return resultList;
	}
	
	/**
	 * 根据组ID查询查询该组下的所有用户 queryType 01普通模糊查询02按首字母模糊查询
	 */
	@Override
	public List<Contact> findContactByContactGroupId(Long contactGroupId,
			String contactQuery, String queryType, Long userAccountId) {
		Assert.notNull(contactGroupId, "组信息ID不能为null");
		boolean permission = groupUtilService.findPermissionByUserAccountId(userAccountId);
		String query_sql;
		query_sql = "select c.contactid as contactId,u.username as ContactName,c.useflag as contactUseFlag from igit_contact_group_relation r "
			+ "left join igit_contact c on r.contactid=c.contactid left join igit_contact_group g on r.groupid=g.groupid "
			+ "left join T_USERMANA_USERINFO u on u.userinfoid=c.userinfoid where (c.delflag is null or c.delflag <>1)";
		if (!permission) {
			query_sql += " and c.useflag=1";
		}
		if (queryType != null) {
			if (queryType.equals("01")) {
				query_sql += " and u.username like '%" + contactQuery + "%'";
			}
			if (queryType.equals("02")) {
				query_sql += " and regexp_like(c.spellname,'^[" + contactQuery
						+ "]')";
			}
		}
		query_sql += " and r.groupid=" + contactGroupId;
		Query query = hibernateEntityDao.getSessionFactory()
				.getCurrentSession().createSQLQuery(query_sql).addScalar(
						"contactId", Hibernate.LONG).addScalar("ContactName")
				.addScalar("contactUseFlag", Hibernate.LONG)
				.setResultTransformer(Transformers.aliasToBean(Contact.class));
		List<Contact> resultList = query.list();
		return resultList;
	}
	
	/**
	 * 查询最近联系人下的用户 queryType 01所有用户组普通模糊查询02所有用户组按首字母模糊查询
	 */
	@Override
	public List<Contact> findContactRecordCountList(Long userInfoId,
			String contactQuery, String queryType, Long userAccountId) {
		Long contactId = contactService.findContactByUserInfoId(userInfoId).getContactId();
		if (contactId != null) {
			boolean permission = groupUtilService.findPermissionByUserAccountId(userAccountId);
			String query_sql;
			query_sql = "select c.contactid as contactId,u.username as ContactName,c.useflag as contactUseFlag from "
				+ " (select distinct t.activecontactid from( select decode(activecontact,'"
				+ contactId
				+ "',passivecontact,activecontact) activecontactid,activecontact,passivecontact,recordid,contactdate from igit_contact_record "
				+ "order by contactdate desc) t where (t.passivecontact="
				+ contactId
				+ " or t.activecontact="
				+ contactId
				+ " )and rownum <=10) r left join igit_contact c "
				+ "on r.activecontactid=c.contactid left join t_usermana_userinfo u on c.userinfoid=u.userinfoid where(c.delflag is null or c.delflag <>1)";
			if (!permission) {
				query_sql += " and c.useflag=1";
			}
			if (queryType != null) {
				if (queryType.equals("01")) {
					query_sql += " and u.username like '%" + contactQuery
							+ "%'";
				}
				if (queryType.equals("02")) {
					query_sql += " and regexp_like(c.spellname,'^["
							+ contactQuery + "]')";

				}
			}
			Query query = hibernateEntityDao.getSessionFactory()
					.getCurrentSession().createSQLQuery(query_sql).addScalar(
							"contactId", Hibernate.LONG).addScalar(
							"ContactName").addScalar("contactUseFlag",
							Hibernate.LONG).setResultTransformer(
							Transformers.aliasToBean(Contact.class));
			List<Contact> resultList = query.list();
			return resultList;
		}
		return null;
	}
}
